package com.thl.levelcache.aop;

import com.thl.levelcache.annotation.LvCache;
import com.thl.levelcache.decoration.LvCacheManager;
import java.lang.reflect.Method;
import java.util.Arrays;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 自定义注解Aop
 */
@Slf4j
@Aspect
@Component
public class LvCacheAop {

  @Autowired
  private LvCacheManager lvCacheManager;

  /***
   * 使用Aop拦截我们的方法上是否使用缓存注解
   * @param lvCache lvCache
   * @param joinPoint joinPoint
   * @return 目标方法返回值
   * @throws Throwable 异常
   */
  @Around(value = "@annotation(lvCache)")
  public Object doAround(ProceedingJoinPoint joinPoint, LvCache lvCache) throws Throwable {
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    // 获取目标方法
    Method targetMethod = methodSignature.getMethod();

    String key = null;
    if (StringUtils.isEmpty(lvCache.key())) {
      // 拼接缓存的key
      key = targetMethod.getName() + Arrays.toString(targetMethod.getParameterTypes()) + Arrays
          .toString(joinPoint.getArgs());
    } else {
      key = lvCache.key();
    }

    return lvCacheManager.getCache(key, targetMethod.getReturnType(), joinPoint);
  }
}